//
//  BTEHomeViewController.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/5.
//

import UIKit
import AVFoundation

enum uploadtype: Int {
    case card =  0
    case face = 1
}

enum cameraT {
    case front
    case back
}

class BTEProductOneViewController: BTEBaseViewController {
    
    var md2: Date?
    var md3: Date?
    
    let server = BTEProductToolNetServer()
    
    var model: BTEProductpeeebonbloidNetModel?
    
    var limodel: BTECarneolfetiniestwgeNetModel?
    
    var pid: String?
    
    var uploadt: uploadtype?
    
    var v: BTEProductOneView {
        return view as! BTEProductOneView
    }
    
    override func loadView() {
        view = BTEProductOneView()
    }

    init(model: BTEProductpeeebonbloidNetModel) {
        self.model = model
        super.init(nibName: nil, bundle: nil)
    }

    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        titleLabel.text = model?.aftermath ?? ""
        
        md2 = Date()
        
        v.imagev.snp.remakeConstraints { make in
            make.left.right.equalToSuperview().inset(16)
            make.top.equalTo(navigationBar.snp.bottom).offset(20)
            make.height.equalTo((UIScreen.main.bounds.width-16) * v.imagev.frame.height / v.imagev.bounds.width)
        }
        
        v.badoy.isUserInteractionEnabled = true
        
        v.clickA = {[weak self] in
            self?.clickA1()
        }
        
        v.clickB = {[weak self] in
            self?.clickB1()
        }

        v.button.addTarget(self, action: #selector(nexta), for: .touchUpInside)
        
        v.badoy.isHidden = true
        
        loadinage()
    }

}



extension BTEProductOneViewController {
    
    func loadinage(){
        BTEHUD.shared.showLoader(on: view)
        server.subsale(data: ["privileger":pid!]) {[weak self] result in
            switch result {
            case .success(let success):
                BTEHUD.shared.hide()
                self?.v.badoy.isHidden = false
                self?.v.a1.text = success?.sidelingwise?.tiniest?.alluviums
                self?.v.a2.text = success?.sidelingwise?.tiniest?.bakerly
                
                if let ima = success?.sidelingwise?.tiniest?.katakinetomer , ima.count > 0 {
                    self?.v.a1imagev.sd_setImage(with: URL.init(string: ima))
                    self?.v.a1tackf.image = UIImage.init(named: "ffew3gggggggg")
                }
                
                if let imaa = success?.sidelingwise?.tiniest?.fermis, imaa.count > 0 {
                    self?.v.a2imagev.sd_setImage(with: URL.init(string: imaa))
                    self?.v.a2tackf.image = UIImage.init(named: "ffew3gggggggg")
                }
                
                self?.limodel = success?.sidelingwise?.tiniest
                
                break
            case .failure(let failure):
                switch failure {
                case .Error(c: let b, m: let bd):
                    BTEHUD.shared.showError(bd, on: (self?.view)!)
                    break
                default:
                    break
                }
                break
            }
        }
    }
    
    // shenfezheng
    @objc func clickA1(){
        uploadt  = .card
        click232()
    }
    
    @objc func clickB1(){
        uploadt  = .face
        click232()
    }
    
    @objc func nexta(){
        click232()
    }
    
    func click232(){
        if limodel?.katakinetomer == "" {
            let aler = BTEIDAlertViewController()
            uploadt  = .card
            aler.modalPresentationStyle = .overFullScreen
            present(aler, animated: false)
            aler.action = {[weak self] in
                aler.dismiss(animated: false)
                self?.needPickPhoto(camera: .back)
            }
            return
        }
        
        if limodel?.fermis == "" {
            md3 = Date()
            let aler = BTEFaceAlertViewController()
            uploadt  = .face
            aler.modalPresentationStyle = .overFullScreen
            present(aler, animated: false)
            aler.action = {[weak self] in
                aler.dismiss(animated: false)
                self?.needPickPhoto(camera: .front)
            }
            return
        }
        
        navigationController?.popViewController(animated: true)
    }
}



extension BTEProductOneViewController :UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    
    func needPickPhoto(camera: cameraT){
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        switch status {
        case .authorized:
            self.haspickphoto(camera: camera)
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { granted in
                DispatchQueue.main.async {
                    if granted {
                        self.haspickphoto(camera: camera)
                    } else {
                        self.loadinfomationAlert()
                    }
                }
            }
        case .denied, .restricted:
            loadinfomationAlert()
        @unknown default:
            break
        }
    }
    
    func haspickphoto(camera: cameraT){
        let picker = UIImagePickerController()
        picker.sourceType = .camera
        picker.delegate = self
        switch camera {
        case .front:
            picker.cameraDevice = .front
        case .back:
            picker.cameraDevice = .rear
        }
        self.present(picker, animated: true)
    }
    
    
    func loadinfomationAlert(){
        let t = BTELanguageManager.shared.localizedString(forKey:"Permission")
        let b = BTELanguageManager.shared.localizedString(forKey:"Camera permission is off. Please enable it in Settings to proceed with verification.")
        let c = BTELanguageManager.shared.localizedString(forKey:"Cancel")
        let e = BTELanguageManager.shared.localizedString(forKey:"Settings")
        let alert = UIAlertController(
            title: t,
            message: b,
            preferredStyle: .alert
        )
                                                          alert.addAction(UIAlertAction(title: c, style: .cancel))
                                                                          alert.addAction(UIAlertAction(title: e, style: .default) { _ in
            if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(settingsURL)
            }
        })
        
        present(alert, animated: true)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let selectedImage = info[.originalImage] as? UIImage {
            switch uploadt! {
            case .card:
                uploadC(selectedImage)
            case .face:
                uploadI(selectedImage)
            }
        }
        picker.dismiss(animated: true)
    }
    
}


extension BTEProductOneViewController {
    
    // 上传card
    fileprivate func uploadC(_ imges: UIImage){
        BTEHUD.shared.showLoader(on: view)
        let data: [String : Any] = ["uncondoled": imges.compressedImageData(maxSize: 1024*101)!,
                    "dikegrave":"11",
                    "reincorporation":"1"]
        server.subvii(data: data) {[weak self] result in
            switch result {
            case .success(let success):
                BTEHUD.shared.hide()
                guard let mo = success?.sidelingwise else {
                    return
                }
                
                let vc = BTEIDInfomationAlertViewController.init()
                vc.modalPresentationStyle = .overFullScreen
                vc.tit2.text = mo.chokier
                vc.b1.text =   mo.jubilar?[0].danknesses
                vc.b2.text =   mo.jubilar?[1].danknesses
                vc.b3.text =   mo.jubilar?[2].danknesses
                vc.t1text.text =   mo.jubilar?[0].questers
                vc.t2text.text =   mo.jubilar?[1].questers
                vc.t3text.text =   mo.jubilar?[2].questers
                
                vc.acti = {[weak self] in
                    vc.t1text.endEditing(true)
                    vc.t2text.endEditing(true)
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "dd-MM-yyyy"
                    dateFormatter.locale = Locale(identifier: "en_US_POSIX")

                    if let date = dateFormatter.date(from: (mo.jubilar?[2].questers ?? "").isEmpty ? "01/01/1900" : (mo.jubilar?[2].questers ?? "")) {
                        let calendar = Calendar.current
                        let year = calendar.component(.year, from: date)
                        let month = calendar.component(.month, from: date)
                        let day = calendar.component(.day, from: date)
                        let time = BTEDateAlertViewController.init(selectedDay: day, selectedMonth: month, selectedYear: year)
                        time.modalPresentationStyle = .overFullScreen
                        time.view.endEditing(true)
                        self?.view.endEditing(true)
                        time.onDateSelected = { t in
                            vc.t3text.text = t
                            vc.dismiss(animated: false)
                        }
                        vc.present(time, animated: false)
                    }
                   
                }
                
                self?.present(vc, animated: false)
                
                vc.action = {[weak self] in
                    
                    vc.t1text.endEditing(true)
                    vc.t2text.endEditing(true)
                    
                    let a =   vc.t1text.text ?? ""
                    let b =   vc.t2text.text ?? ""
                    let c =   vc.t3text.text ?? ""
                    
                    BTEHUD.shared.showLoader(on: (vc.view))
                    var data:[String:String] = ["privileger":(self?.pid)!]
                    data["manificum"] = a
                    data["malabarese"] = b
                    data["unextendedness"] = c
                    self?.server.undonated(data: data) { result in
                        switch result {
                        case .success(let success):
                            
                            let t = TrackingEvent.init(step: "2", startTimestamp: "\((self?.md2)!.timeIntervalSince1970)", endTimestamp: "\(Date().timeIntervalSince1970)")
                            BTELocationReporterManager.shared.reportLocation(for: t)
                            
                            BTEHUD.shared.hide()
                            vc.dismiss(animated: false)
                            self?.loadinage()
                            break
                        case .failure(let failure):
                            switch failure {
                            case .Error(c: let b, m: let bd):
                                BTEHUD.shared.showError(bd, on: vc.view)
                                break
                            default:
                                break
                            }
                           break
                        }
                    }
                }
                
                break
            case .failure(let failure):
                switch failure {
                case .Error(c: let b, m: let bd):
                    BTEHUD.shared.showError(bd, on: (self?.view)!)
                    break
                default:
                    break
                }
                break
            }
        }
    }
    
    // 上传id
    fileprivate func uploadI(_ imges: UIImage){
        BTEHUD.shared.showLoader(on: view)
        let data = ["uncondoled": imges.compressedImageData(maxSize: 1024*101)!,
                    "dikegrave":"10",
                    "reincorporation":"1"] as [String : Any]
        server.subvii(data: data) {[weak self] result in
            switch result {
            case .success(let success):
                BTEHUD.shared.hide()
                guard let mo = success?.sidelingwise else {
                    return
                }
                
                let t = TrackingEvent.init(step: "3", startTimestamp: "\((self?.md3)!.timeIntervalSince1970)", endTimestamp: "\(Date().timeIntervalSince1970)")
                BTELocationReporterManager.shared.reportLocation(for: t)
                
                
                self?.loadinage()
                break
            case .failure(let failure):
                switch failure {
                case .Error(c: let b, m: let bd):
                    BTEHUD.shared.showError(bd, on: (self?.view)!)
                    break
                default:
                    break
                }
                break
            }
        }
    }
    
}
